<template>
  <div>
    <button class="button" @click="showDialog = true">添加</button>
    <Transition name="fade">
      <div v-if="showDialog" class="dialog-overlay">
        <div class="dialog">
          <h2 class="dialog-title">添加信息</h2>
          <form @submit.prevent="handleSubmit">
            <div class="form-item">
              <label for="file_name">文件名称:</label>
              <input v-model="formData.fileName" type="text" id="file_name" required />
            </div>
            <div class="form-item">
              <label for="title">标题:</label>
              <input v-model="formData.title" type="text" id="title" required />
            </div>
            <div class="form-item">
              <label for="type_id">类型 ID:</label>
              <input v-model="formData.typeId" type="text" id="type_id" required />
            </div>
            <div class="form-item">
              <label for="image">图片:</label>
              <input type="file" @change="handleFileUpload" id="image" />
              <div v-if="imageName">
                <span>上传成功文件名：{{ imageName }}</span>
              </div>
            </div>
            <div class="form-item">
              <label for="uploadTime">时间:</label>
              <input v-model="formData.uploadTime" type="datetime-local" id="uploadTime" required />
            </div>
            <div class="button-container">
              <button type="submit" class="button">确定</button>
              <button @click="showDialog = false" type="button" class="button">取消</button>
            </div>
          </form>
        </div>
      </div>
    </Transition>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import axios from 'axios';

// 控制对话框的显示状态
const showDialog = ref(false);

// 存储表单数据
const formData = ref({
  fileName: '',
  title: '',
  typeId: '',
  image: '',
  uploadTime: '',
  consultantId: 0,
});

// 存储图片名称
const imageName = ref('');

// 获取 consultantId 从 localStorage
const initConsultantId = () => {
  const value = JSON.parse(localStorage.getItem('key'));
  if (value && value.data && value.data.consultantId) {
    formData.value.consultantId = value.data.consultantId;
  } else {
    console.warn('未找到 consultantId 或存储的数据结构不符合预期');
    // 设置默认值或采取其他处理方式
    formData.value.consultantId = 1;
  }
};

// 处理文件上传
const handleFileUpload = (event) => {
  const file = event.target.files[0];
  if (!file) {
    alert('请选择文件！');
    return;
  }

  // 创建 FormData 对象并添加文件
  const uploadFormData = new FormData();
  uploadFormData.append('file', file);

  // 调用文件上传接口
  axios
      .post('http://127.0.0.1:9090/file/uploadsn', uploadFormData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
      .then((response) => {
        console.log('文件上传成功：', response.data);

        // 验证返回数据结构
        const additionalData = response?.data?.additionalData;
        const fileNames = additionalData?.fileNames[0];

        if (fileNames) {
          formData.value.image = fileNames; // 使用上传的第一个文件名
          imageName.value = fileNames; // 显示上传成功的文件名
        } else {
          alert('上传失败，未获取到文件名！');
        }
      })
      .catch((error) => {
        console.error('文件上传失败：', error);
        alert('文件上传失败，请重试！');
      });
};

// 处理表单提交
const handleSubmit = () => {
  // 确保时间是 ISO 8601 格式，如果时间为空，设置为当前时间
  if (!formData.value.uploadTime) {
    formData.value.uploadTime = new Date().toISOString();
  }
  console.log('提交的表单数据：', formData.value);

  // 提交数据到接口
  axios
      .post('http://127.0.0.1:9090/Audio', formData.value)
      .then((response) => {
        console.log('数据提交成功：', response.data);
        alert('添加成功！');
        showDialog.value = false;
      })
      .catch((error) => {
        console.error('数据提交失败：', error);
        alert('添加失败，请重试！');
      });
};

// 初始化 consultantId
onMounted(() => {
  initConsultantId();
});
</script>

<style scoped>
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  width: 500px;
  height: 470px;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.form-item {
  display: flex;
  flex-direction: column;
}

.form-item input {
  height: 30px;
  font-size: 16px;
}

.button-container {
  display: flex;
  justify-content: space-evenly;
}

.button {
  height: 25px;
  font-size: 14px;
  background-color: rgba(64, 158, 255, 0.81);
  width: 100px;
  text-align: center;
  cursor: pointer;
  border-radius: 10px;
  color: white;
  border: none;
}

.dialog-title {
  font-size: 20px;
  margin: 0;
  text-align: center;
}
</style>
